public class Main {
    /*
     * 填充每一个节点的下一个右侧节点
     * BFS
     * */
    class aNode {
        public int val;
        public aNode left;
        public aNode right;
        public aNode next;

        public aNode() {
        }

        public aNode(int _val) {
            val = _val;
        }

        public aNode(int _val, aNode _left, aNode _right, aNode _next) {
            val = _val;
            left = _left;
            right = _right;
            next = _next;
        }
    }

    ;

    public aNode connect2(aNode root) {
        if (root == null) {
            return root;
        }
        Queue<aNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            aNode pre = queue.peek();
            while (size > 0) {
                aNode node = queue.poll();
                if (pre != node) {
                    pre.next = node;
                    pre = node;
                }
                if (node.left != null) {
                    queue.offer(node.left);
                    queue.offer(node.right);
                }
                size--;
            }
        }
        return root;
    }

    /*
     * DFS
     *
     *
     * */
    public void Connection(aNode root) {
        if (root == null) {
            return;
        }
        aNode curLeft = root.left;
        aNode curRight = root.right;
        while (curLeft != null && curRight != null) {
            curLeft.next = curRight;
            curLeft = curLeft.right;
            curRight = curRight.left;
        }
        Connection(root.left);
        Connection(root.right);
    }

    public aNode connect(aNode root) {
        if (root == null) {
            return root;
        }
        Connection(root);
        return root;
    }
}